<template>
	<page-wraper :safeAreaInsetBottom="false">
		<view>
			<wd-notice-bar text="订单清关信息上限为3个" prefix="warn-bold" />
			
			<wd-swipe-action v-for="(item, index) in items" :key="index">
				<wd-cell :title="`${item.description}`" :value="`${item.pieces} 件 - ${item.weight} lbs`"
					@click="() => viewDetail(item)" />
				<template #right>
					<view class="action">
						<view class="button delete" @click="() => remove(index)">删除</view>
						<view class="button edit" @click="() => edit(index, item)">编辑</view>
					</view>
				</template>
			</wd-swipe-action>
		</view>

		<wd-action-sheet v-model="showDetailModal" title="物品详情">
			<wd-cell-group>
				<wd-cell title="中文品名" :value="currentItem.description" />
				<wd-cell title="英文品名" :value="currentItem.description_en" />
				<wd-cell title="税号" :value="currentItem.hsc_code || '-'" />
				<wd-cell title="数量" :value="`${currentItem.pieces} pcs`" />
				<wd-cell title="单个重量" :value="`${currentItem.weight} lbs`" />
				<wd-cell title="单个价值" :value="`${currentItem.declared_value} ${currentItem.declared_value_currency}`" />
				<wd-cell title="原产国" :value="getCountryName(currentItem.manufacture_country_code)" />
			</wd-cell-group>
			<view class="button-group">
				<wd-button type="primary" @click="closeDetail">关闭</wd-button>
			</view>
		</wd-action-sheet>

		<wd-action-sheet v-model="showEditModal" title="编辑物品">
			<wd-notice-bar :text="orderType === 'OLD' ? `单票申报总价值不超过RMB${maxDeclareValue}，旧物可按1-3折合理折旧申报` : `单票申报总价值不超过RMB${maxDeclareValue}`" prefix="warn-bold" />
			
			<wd-form ref="form2" :model="editRow" :rules="rules">
				<wd-cell-group border>
					<wd-picker label="包裹" label-width="100px" prop="package_id"
						v-model="editRow.package_id" :columns="packages" />
					<wd-input label="中文品名" label-width="100px" prop="description" v-model="editRow.description"
						placeholder="请输入中文品名" />
					<wd-input label="英文品名" label-width="100px" prop="description" v-model="editRow.description_en"
						placeholder="请输入英文品名" />
					<wd-picker :columns="taxsColumns" label-width="100px" required label="税号"
						v-model="editRow.hsc_codes" :column-change="onChangeTax" />
					<wd-input type="digit" label="数量" label-width="100px" prop="pieces" v-model="editRow.pieces"
						placeholder="请输入数量">
						<template #suffix>
							<span>pcs</span>
						</template>
					</wd-input>
					<wd-input type="digit" label="单个重量" label-width="100px" prop="weight" v-model="editRow.weight"
						placeholder="请输入重量">
						<template #suffix>
							<span>lbs</span>
						</template>
					</wd-input>
					<wd-input type="digit" label="单个价值" label-width="100px" prop="declared_value"
						v-model="editRow.declared_value" placeholder="请输入单个价值" />
					<wd-picker label="价值币种" label-width="100px" prop="declared_value_currency"
						v-model="editRow.declared_value_currency" :columns="currencies" />
					<wd-picker label="原产国" label-width="100px" v-model="editRow.manufacture_country_code"
						:columns="countries" />
				</wd-cell-group>

				<view class="button-group">
					<wd-button type="info" plain @click="cancelEdit">取消</wd-button>
					<wd-button type="primary" @click="confirmEdit">确认</wd-button>
				</view>
			</wd-form>
		</wd-action-sheet>
		
		<wd-tabbar fixed bordered safeAreaInsetBottom placeholder v-if="items.length < 3 && !showEditModal">
			<wd-button icon="add" block @click="add">添加物品</wd-button>
		</wd-tabbar>
	</page-wraper>
</template>

<script lang="ts" setup>
	import { ref, watch } from 'vue'
	import type { FormItemRule } from 'wot-design-uni'
	import { onLoad } from '@dcloudio/uni-app'

	interface Item {
		description : string;
		description_en : string;
		sku : string;
		hsc_code : string;
		hsc_codes : string[];
		pieces : string | number;
		weight : string | number;
		weight_unit ?: string;
		declared_value : string | number;
		declared_value_currency : string;
		manufacture_country_code : string;
		package_id : string;
	}

	const items = ref<Item[]>([]);
	const editIndex = ref<number>(-1);
	const editRow = ref<Item>({
		description: '',
		description_en: '',
		sku: '',
		hsc_code: '',
		hsc_codes: [],
		pieces: '',
		weight: '',
		declared_value: '',
		declared_value_currency: 'USD',
		manufacture_country_code: 'CN',
		package_id: ''
	});
	// 修改表单验证规则部分，添加类型定义
	const rules : Record<string, FormItemRule[]> = {
		description: [
			{ required: true, message: '请输入中文品名' }
		],
		description_en: [
			{ required: true, message: '请输入英文品名' }
		],
		pieces: [
			{ required: true, message: '请输入数量' },
			{ required: true, validator: (val : string | number) => validateNumber(val, '数量') }
		],
		weight: [
			{ required: true, message: '请输入重量' },
			{ required: true, validator: (val : string | number) => validateNumber(val, '重量') }
		],
		declared_value: [
			{ required: true, message: '请输入单个价值' },
			{ required: true, validator: (val : string | number) => validateNumber(val, '单个价值') }
		],
		hsc_code: [
			{ required: true, message: '请选择税号' }
		],
		package_id: [
			{ required: true, message: '请选择包裹' }
		]
	};
	const showEditModal = ref(false);
	const form2 = ref();
	const currencies = ref([]);
	const countries = ref([]);
	const taxs = ref<any>({});
	const taxsColumns = ref<any>([]);
	const showDetailModal = ref(false);
	const currentItem = ref<Item>({
		description: '',
		description_en: '',
		sku: '',
		hsc_code: '',
		hsc_codes: [],
		pieces: '',
		weight: '',
		declared_value: '',
		declared_value_currency: 'USD',
		manufacture_country_code: 'CN',
		package_id: ''
	});
	const maxDeclareValue = ref(0);
	const orderType = ref('OLD');
	const packages = ref([]);

	watch(items, (newVal) => {
		uni.$emit('changeItems', newVal);
	}, { deep: true });
	
	onLoad((query: any) => {
		items.value = JSON.parse(decodeURIComponent(query.items));
		orderType.value = query.orderType;
		
		const ps = JSON.parse(decodeURIComponent(query.packages));
		
		for (var i = 0; i < ps.length; i++) {
			packages.push({
				value: ps[i].id,
				label: `${ps[i].length} x ${ps[i].width} x ${ps[i].height}`
			});
		}
		
		Promise.all([
			uni.$http.get('/main/currencies'),
			uni.$http.get('/main/countries'),
			uni.$http.get(query.orderType === 'NEW' ? '/main/taxs2_new': '/main/taxs2'),
			uni.$http.get('/system_config/basic/max_declare_value'),
		]).then(([currenciesRes, countriesRes, taxsRes, dvRes]) => {
			currencies.value = currenciesRes.data.data.map(a => ({ value: a.currency, label: a.currency, exchange_rate: a.exchange_rate }));
			countries.value = countriesRes.data.data.map(a => ({ value: a.code2, label: a.name }));
			taxs.value = taxsRes.data.data;
			maxDeclareValue.value = Number(dvRes.data.data) || 0;
			
			rendertaxControl();
		});
	});

	function rendertaxControl() {
		taxsColumns.value = [];

		function x(index) {
			var value = editRow.value.hsc_codes[index - 1] || taxsColumns.value[index - 1][0].value;

			if (!editRow.value.hsc_codes[index - 1]) {
				editRow.value.hsc_codes.push(taxsColumns.value[index - 1][0].value);
			}

			if (taxs.value[value]) {
				taxsColumns.value.push(taxs.value[value]);

				x(index + 1);
			}
		}

		taxsColumns.value.push(taxs.value['0']);
		
		x(1);
	}

	function onChangeTax(pickerView, value, columnIndex, resolve) {
		const item = value[columnIndex] || value;
		
		if (item) {
			editRow.value.hsc_codes[item.deep] = item.value;

			while (editRow.value.hsc_codes.length > item.deep + 1) {
				editRow.value.hsc_codes.splice(item.deep + 1, 1);
			}

			rendertaxControl();
		}

		resolve()
	}

	function add() {
		if (items.value.length >= 3) return;
		
		editIndex.value = -1;
		editRow.value = {
			description: '',
			description_en: '',
			sku: '',
			hsc_code: '',
			hsc_codes: [],
			pieces: '',
			weight: '',
			declared_value: '',
			declared_value_currency: 'USD',
			manufacture_country_code: ''
		};
		showEditModal.value = true;
	}

	function edit(index : number, item : any) {
		editIndex.value = index;
		editRow.value = { ...item };
		showEditModal.value = true;

		rendertaxControl();
	}

	function remove(index : number) {
		items.value.splice(index, 1);
	}

	// 修改验证函数的返回类型
	const validateNumber = (value : string | number, type : string) : boolean | string => {
		const num = Number(value);
		if (isNaN(num)) {
			return `请输入正确的${type}`;
		}
		if (num <= 0) {
			return `${type}必须大于0`;
		}
		return true;
	};

	// 修改 confirmEdit 函数
	async function confirmEdit() {
		editRow.value.hsc_code = editRow.value.hsc_codes.at(-1);
		
		var declareValue = 0;
		
		const cs = (item: any) => {
			const c = currencies.value.find(a => a.value === item.declared_value_currency);
			
			if (c) {
				return (Number(item.declared_value) || 0) * (Number(item.pieces) || 1) * c.exchange_rate;
			}
			
			return 0;
		}
		
		for (var i = 0; i < items.value.length; i++) {
			if (i != editIndex.value) {
				declareValue += cs(items.value[i]);
			}
		}
		
		if (maxDeclareValue.value > 0 && (declareValue + cs(editRow.value)) > maxDeclareValue.value) {
			return uni.showToast({
				title: `申报总价值不能超过${maxDeclareValue.value}RMB, 当前已填写${(declareValue + cs(editRow.value)).toFixed(2)}RMB`,
				icon: 'none'
			});
		}
		
		await form2.value.validate().then((res: any) => {
			console.log(res);
			if (res.valid) {
				const data = {
					...editRow.value
				};

				if (editIndex.value !== -1) {
					items.value[editIndex.value] = data;
					editIndex.value = -1;
				} else {
					items.value.push(data);
				}
				showEditModal.value = false;
				editRow.value = {
					description: '',
					description_en: '',
					sku: '',
					hsc_code: '',
					hsc_codes: [],
					pieces: '',
					weight: '',
					declared_value: '',
					declared_value_currency: 'USD',
					manufacture_country_code: ''
				};
			} else {
				uni.showToast({
					title: res.errors[0].message,
					icon: 'none'
				});
			}
		}).catch(() => {
			uni.showToast({
				title: '请输入正确的内容',
				icon: 'none'
			});
		});
	}

	function cancelEdit() {
		showEditModal.value = false;
		editRow.value = {
			description: '',
			sku: '',
			hsc_code: '',
			hsc_codes: [],
			pieces: '',
			weight: '',
			declared_value: '',
			declared_value_currency: 'USD',
			manufacture_country_code: 'CN'
		};
		editIndex.value = -1;
	}

	function viewDetail(item : Item) {
		currentItem.value = { ...item };
		showDetailModal.value = true;
	}

	function closeDetail() {
		showDetailModal.value = false;
	}

	function getCountryName(code : string) : string {
		const country = countries.value.find(c => c.value === code);
		return country ? country.label : code;
	}
</script>

<style lang="scss" scoped>
	:deep(.page-wraper) {
		background: #f6f6f6;
	}

	.button-group {
		display: flex;
		justify-content: space-around;
		padding: 20px;

		:deep(.wd-button) {
			width: 40%;
		}
	}

	.package-info {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		font-size: 14px;
		color: #666;

		text {
			display: block;
			line-height: 1.4;

			&:last-child {
				color: #999;
				font-size: 12px;
			}
		}
	}

	.action {
		display: flex;
		height: 100%;

		.button {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 80px;
			color: #fff;
			font-size: 14px;

			&.delete {
				background-color: #fa4350; // 红色
			}

			&.edit {
				background-color: #4d80f0; // primary蓝色
			}
		}
	}

	:deep(.wd-cell) {
		.wd-cell__title {
			color: #666;
			font-size: 14px;
		}

		.wd-cell__value {
			color: #333;
			font-size: 14px;
		}
	}

	.button-group {
		display: flex;
		justify-content: center;
		padding: 20px;

		:deep(.wd-button) {
			width: 40%;
		}
	}
</style>